<template>
  <!-- 导入授权 -->
  <div class="grid-content bg-purple">
    <div class="header_select">
      <div>
        <el-button type="primary" @click="thetemplate()" size="mini">execl模板下载</el-button>
      </div>
      <div class="bulk_import">
        <el-upload
          class="upload-demo"
          action
          :on-change="handleChange"
          :on-exceed="handleExceed"
          :on-remove="handleRemove"
          :file-list="fileListUpload"
          :limit="limitUpload"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :auto-upload="false"
        >
          <el-button type="primary" @click="handleclickto()" size="mini">浏览文件</el-button>
        </el-upload>
      </div>
      <div class="packge_batch">
        <el-button type="primary" @click="packgebatchto()" size="mini">导入数据</el-button>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="changestudentlist"
      ref="table"
      border
      highlight-current-row
      style="width: 100%"
      :header-cell-style="header => headFirst(header, 2)"
      @selection-change="handleSelectionChange"
      height="calc(100vh - 230px)"
      size="mini"
      :cell-style="(res) => headFirst_col(res, [])"
    >
      <!-- <el-table-column type="selection" width="55" align="center"></el-table-column> -->
      <el-table-column label="是否选中" prop="isCheck" align="center" width="40" >
        <template slot="header" slot-scope="scope">
          <el-checkbox :value="isSelectAll" @change="CheckSelectAll" :disabled="isError" />
        </template>
        <template slot-scope="scope">
          <el-checkbox
            :value="scope.row.isCheck"
            @change="(isCheck) =>CheckSelect(isCheck,scope.row)"
            :disabled="isError"
          />
        </template>
      </el-table-column>
      <el-table-column label="错误原因" prop="errorStr" v-if="isError"></el-table-column>
      <el-table-column prop="buildingName" label="楼栋" align="center"></el-table-column>
      <el-table-column prop="roomName" label="房间号" align="center"></el-table-column>
      <el-table-column prop="cardNumber" label="卡号" align="center"></el-table-column>
      <!-- 有效时间 -->
      <el-table-column prop="startTime" label="有效开始时间" align="center" min-width="150px"></el-table-column>
      <el-table-column prop="endTime" label="有效结束时间" align="center" min-width="150px"></el-table-column>
      <el-table-column prop="backLock" label="反锁开门" align="center" width="40px"></el-table-column>
      <!-- 开门-礼拜 -->
      <el-table-column prop="Sunday" label="星期" align="center">
        <el-table-column prop="monday" label="一" align="center" width="40px"></el-table-column>
        <el-table-column prop="tuesday" label="二" align="center" width="40px"></el-table-column>

        <el-table-column prop="wednesday" label="三" align="center" width="40px" :disabled="true"></el-table-column>
        <el-table-column prop="thursday" label="四" align="center" width="40px"></el-table-column>

        <el-table-column prop="friday" label="五" align="center" width="40px"></el-table-column>

        <el-table-column prop="saturday" label="六" align="center" width="40px"></el-table-column>

        <el-table-column prop="sunday" label="日" align="center" width="40px"></el-table-column>
      </el-table-column>

      <!-- 星期时段 -->
      <el-table-column prop="SundayTime" label="星期时段" align="center">
        <el-table-column prop="mondayTimeStageIndex" label="一" align="center" width="38px"></el-table-column>
        <el-table-column prop="tuesdayTimeStageIndex" label="二" align="center" width="38px"></el-table-column>

        <el-table-column prop="wednesdayTimeStageIndex" label="三" align="center" width="38px"></el-table-column>

        <el-table-column prop="thursdayTimeStageIndex" label="四" align="center" width="38px"></el-table-column>
        <el-table-column prop="fridayTimeStageIndex" label="五" align="center" width="38px"></el-table-column>
        <el-table-column prop="saturdayTimeStageIndex" label="六" align="center" width="38px"></el-table-column>
        <el-table-column prop="sundayTimeStageIndex" label="日" align="center" width="38px"></el-table-column>
      </el-table-column>
      <!-- 假日时段 -->
      <el-table-column prop="holidayTimeStageIndex" label="假日时段" align="center" width="40px"></el-table-column>
      <el-table-column prop="password" label="密码" align="center"></el-table-column>
      <el-table-column prop="doorType" label="门锁类型" align="center"></el-table-column>
      <el-table-column prop="userNumber" label="人员编号" align="center"></el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        @size-change="handleSizeChangeY"
        @current-change="handleCurrentChangepageY"
        :current-page="pageY"
        :page-sizes="[20,40, 80,120]"
        :page-size="pageSizeY"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalY"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import { JSEncrypt } from 'jsencrypt'
export default {
  data() {
    return {
      isError: false,
      loading: false,
      fileListUpload: [],
      limitUpload: 1,
      table1: true,
      changestudentlist: [],
      changestudentSelect: [],
      changestudentlist: [],
      // 错误信息显示
      isError: false,
      // 是否全选
      isSelectAll: false,
      // 分页变量
      changestudentY: [],
      // 原始页数
      pageY: 1,
      // 每条个数
      pageSizeY: 20,
      // 总条数
      totalY: 0
    }
  },
  computed: {
    changeschoolid: {
      get() {
        return this.$store.state.user.changeschoolid
      }
    }
  },
  methods: {
    handleSelectionChange(val) {
      this.changestudentSelect = val
    },
    //excel模板下载
    thetemplate() {
      this.$http({
        url: this.$http.adornUrl(
          '/terminal/doorLock/poi-lock-empower-download'
        ),
        method: 'post',
        data: this.$http.adornData({}),
        responseType: 'blob'
      }).then(({ data }) => {
        console.log(data)
        this.downloadFile(data)
      })
    },
    // 文件下载
    downloadFile(data) {
      // 文件导出
      if (!data) {
        return
      }
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', '门锁导入批量模板.xlsx')
      document.body.appendChild(link)
      link.click()
    },
    //导入excel相关
    handleRemove(file, fileList) {
      // 初始化
      this.isError = false
      this.changestudentlist = []
      this.changestudentSelect = []
      this.fileTemp = null
    },
    //导入excel相关
    handleChange(file, fileList) {
      console.log(file)
      this.fileTemp = file.raw
      if (this.fileTemp) {
        if (
          this.fileTemp.type ==
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          this.fileTemp.type == 'application/vnd.ms-excel'
        ) {
          this.changestudentlist = []
          this.table1 = true
          this.importfxx(this.fileTemp)
        } else {
          this.$message({
            type: 'warning',
            message: '附件格式错误，请删除后重新上传！'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请上传附件！'
        })
      }
    },
    //导入excel相关
    handleExceed(file, fileList) {
      console.log(2)
      fileList[0].name = file[0].name
      this.fileTemps = file[0]
      if (this.fileTemps) {
        if (
          this.fileTemps.type ==
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          this.fileTemps.type == 'application/vnd.ms-excel'
        ) {
          this.changestudentlist = []
          this.table1 = true
          this.importfxx(this.fileTemps)
        } else {
          this.$message({
            type: 'warning',
            message: '附件格式错误，请删除后重新上传！'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请上传附件！'
        })
      }
    },
    // 时间转换
    getdata(date) {
      // let date = 44120
      date = Math.round(date * 100000) / 100000
      var Minustime = 1.33333 * 24 * 3600000
      date = new Date(date * 24 * 3600000 - Minustime)
      date.setYear(date.getFullYear() - 70)
      return this.dateFormat('YYYY-mm-dd', date)
    },
    dateFormat(fmt, date) {
      let ret
      const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      // console.log(opt)
      for (let k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
          )
        }
      }
      return fmt
    },
    /**
     * 导入相关函数
     */
    // 数据初始化
    initList() {
      // 关闭加载
      this.importLoad = false
      // 渲染表格初始化
      this.changestudentlist = []
      // 表格中拿出的原始数据
      this.changestudentY = []
      // 原始页数
      this.pageY = 1
      // 每条个数
      this.pageSizeY = 20
      // 总条数
      this.totalY = 0
      // 原始的显示数据数
      this.showPageSizeY = 20
      this.isSelectAll = false
      this.isError = false
    },
    // 获取到用户数据，页面渲染
    getUserList(pagenum, pagesize) {
      this.changestudentlist = this.changestudentY.slice(
        (pagenum - 1) * pagesize,
        pagenum * pagesize
      )
    },
    // 选中数据
    CheckSelect(val, row) {
      // 因为是用索引当做id的。
      this.changestudentY[row.id].isCheck = val
    },
    // 全选按钮
    CheckSelectAll(val) {
      this.isSelectAll = val
      this.changestudentY.map(item => {
        item.isCheck = val
      })
    },
    // 导入数据处理
    getData() {
      let arr = []
      this.changestudentY.map(item => {
        if (item.isCheck) {
          arr.push(item)
        }
      })
      return arr
    },
    // 用户导入分页
    handleSizeChangeY(val) {
      this.pageSizeY = val
      this.getUserList(this.pageY, this.pageSizeY)
    },
    handleCurrentChangepageY(val) {
      this.pageY = val
      this.getUserList(this.pageY, this.pageSizeY)
    },

    // 处理文件信息
    importfxx(obj) {
      this.isError = false
      console.log(obj)
      let _this = this
      _this.loading = true
      // 通过DOM取文件数据
      this.file = obj
      var rABS = false //是否将文件读取为二进制字符串
      var f = this.file
      var reader = new FileReader()
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function(f) {
        var binary = ''
        var rABS = false //是否将文件读取为二进制字符串
        var pt = this
        var wb //读取完成的数据
        var outdata
        var reader = new FileReader()
        reader.onload = function(e) {
          var bytes = new Uint8Array(reader.result)
          var length = bytes.byteLength
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
          }
          var XLSX = require('xlsx')
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: 'base64'
            })
          } else {
            wb = XLSX.read(binary, {
              type: 'binary'
            })
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]) //outdata就是你想要的东西
          this.da = [...outdata]
          let arr = []
          this.da.map(v => {
            let obj = {}
            obj.buildingName = v['楼栋']
            obj.roomName = v['房 间 号']
            obj.cardNumber = v['卡号']
            obj.startTime = v['有效开始时间']
            obj.endTime = v['有效结束时间']
            obj.monday = v['星期一是否可开']
            obj.tuesday = v['星期二是否可开']
            obj.wednesday = v['星期三是否可开']
            obj.thursday = v['星期四是否可开']
            obj.friday = v['星期五是否可开']
            obj.saturday = v['星期六是否可开']
            obj.sunday = v['星期日是否可开']
            obj.backLock = v['反锁开门']
            obj.holidayTimeStageIndex = v['假日时段']
            obj.mondayTimeStageIndex = v['周一时段']
            obj.tuesdayTimeStageIndex = v['周二时段']
            obj.wednesdayTimeStageIndex = v['周三时段']
            obj.thursdayTimeStageIndex = v['周四时段']
            obj.fridayTimeStageIndex = v['周五时段']
            obj.saturdayTimeStageIndex = v['周六时段']
            obj.sundayTimeStageIndex = v['周日时段']
            obj.password = v['密码']
            obj.doorType = v['门锁类型']
            obj.userNumber = v['人员编号']
            arr.push(obj)
          })
          _this.changestudentlist = [...arr]
          let arrto = JSON.parse(JSON.stringify(_this.changestudentlist))
          console.log(arrto)
          let add11 = []
          if (arrto.length > 0) {
            arrto.map((item, index) => {
              // if (
              //   item.buildingName == undefined ||
              //   item.roomName == undefined ||
              //   item.cardNumber == undefined ||
              //   item.endTime == undefined
              // ) {
              //   return false;
              // }
              item.startTime = _this.getdata(item.startTime)
              item.endTime = _this.getdata(item.endTime)
              item.isCheck = _this.isSelectAll
              item.id = index
              add11.push(item)
            })
          }
          _this.changestudentY = arrto
          _this.getUserList(_this.pageY, _this.pageSizeY)
          _this.totalY = arrto.length
          // bug
          // _this.changestudentlist = arrto;
          console.log(_this.changestudentlist)
          _this.loading = false
        }
        reader.readAsArrayBuffer(f)
      }

      if (rABS) {
        reader.readAsArrayBuffer(f)
      } else {
        reader.readAsBinaryString(f)
      }
    },
    // 文件提交
    packgebatchto() {
      // if (this.changestudentlist[0] && this.changestudentlist[0].errorStr) {
      //   this.$message({
      //     message: "数据非法,无非导入",
      //     type: "warning",
      //   });
      //   return;
      // }
      if (this.loading) {
        this.$message({
          showClose: true,
          message: '正在批量授权请勿重复操作',
          type: 'warning',
          duration: '500'
        })
        return false
      }
      if (this.changestudentlist.length == 0) {
        this.$message({
          message: '没有批量数据',
          type: 'warning'
        })
        return false
      }
      this.loading = true
      let arrList = this.changestudentlist.filter(item => item.isCheck)
      this.$http({
        url: this.$http.adornUrl('/terminal/doorLock/empower-name-excel-add'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            nameExcelList: arrList,
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        this.loading = false
        this.initList()
        // console.log(data)
        if (data.messageCode == 500) {
          this.$message({
            message: data.errorMessage,
            type: 'warning'
          })
        }
        if (data.messageCode == 200) {
          // if (data.messageContent.errorList) {
          // this.changestudentY = data.messageContent.errorList;
          if (data.messageContent) {
            this.changestudentY = data.messageContent
            this.totalY = this.changestudentY.length
            this.getUserList(this.pageY, this.pageSizeY)
            this.isError = true
            this.$message({
              // message: data.messageContent.errorStr,
              message: '部分导入成功',
              type: 'warning'
            })
            this.$nextTick(() => {
              this.$refs['table'].doLayout()
            })
          } else {
            this.$message({
              message: '批量录入成功',
              type: 'success'
            })
          }
          // this.$message({
          //   message: "批量录入成功",
          //   type: "success",
          // });
        } else {
          this.$message({
            message: data.errorMessage,
            type: 'warning'
          })
        }
      })
    },
    handleclickto() {}
  }
}
</script>
<style lang="scss" scoped>
.grid-content {
  padding: 10px;
  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }

  .page {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.header_select {
  height: 40px;
  // background-color: #F5F5F5;
  width: 100%;
  display: flex;
  align-items: center;
  // padding: 0 20px;
  padding-bottom: 10px;
  .cardnumber,
  .username,
  .usernumber {
    display: flex;
    align-items: center;
    padding-left: 10px;
    width: 200px;
    div:nth-child(1) {
      width: 40px;
    }
  }
  .searchbutton {
    // height:36px;
    padding-left: 10px;
    display: flex;
    flex: 1;
    justify-content: space-between;
    .addstudent {
      padding-right: 20px;
    }
    .el-checkbox {
      // align-self: left;
      width: 150px;
      margin-top: 20px;
    }
  }
  .bulk_import {
    padding-left: 20px;
    .upload-demo {
      display: flex;
      align-items: center;
      /deep/.el-upload-list__item-name {
        margin-right: 22px;
      }
    }
  }
  .packge_batch {
    padding-left: 20px;
  }
}
</style>